package com.cyj.dream.auth.entity;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.cyj.dream.auth.persistence.service.ITbSysRoleService;
import com.cyj.dream.core.base.SysBaseEntity;
import com.cyj.dream.core.constant.users.SexConverter;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.persistence.*;
import java.io.Serializable;
import java.util.*;

/**
 * @Description: 用户实体类
 * @BelongsProject: dream-DreamChardonnay
 * @BelongsPackage: com.cyj.dream.auth.model
 * @Author: ChenYongJia
 * @CreateTime: 2021-04-01 09:52
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@TableName("dream_sys_user")
@ApiModel(value = "SysUser用户对象", description = "dream_sys_user 用户实体")
public class SysUser extends SysBaseEntity implements UserDetails, Serializable {

    @ApiModelProperty(value = "用户名称")
    @Column(columnDefinition = "varchar(64) NOT NULL COMMENT '用户名称'  ")
    @ExcelProperty("用户名称")
    private String userName;

    @ApiModelProperty(value = "用户登陆密码")
    @Column(columnDefinition = "varchar(256) COMMENT '用户登陆密码'  ")
    @ExcelIgnore
    private String userPassword;

    @Column(columnDefinition = "tinyint(3) DEFAULT 1 COMMENT '用户年龄'")
    @ApiModelProperty(value = "用户年龄", example = "1")
    @ExcelProperty("用户年龄")
    private Integer sysUserAge;

    @ApiModelProperty(value = "用户生日")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    @ExcelProperty("用户生日")
    private Date sysUserBirthday;

    @ApiModelProperty(value = "用户手机号")
    @Column(columnDefinition = "varchar(11) COMMENT '用户手机号'  ")
    @ExcelProperty("用户手机号")
    private String sysUserPhone;

    @Column(columnDefinition = "tinyint(3) DEFAULT 1  COMMENT '用户性别（0 未知 1 男 2 女）'")
    @ApiModelProperty(value = "用户性别（0 未知 1 男 2 女）", example = "1")
    @ExcelProperty(value = "用户性别（0 未知 1 男 2 女）", converter = SexConverter.class)
    private Integer sysUserSex;

    @ApiModelProperty(value = "用户邮箱")
    @Column(columnDefinition = "varchar(100) COMMENT '用户邮箱'  ")
    @ExcelProperty("用户邮箱")
    private String sysUserEmail;

    @ApiModelProperty(value = "用户地址")
    @Column(columnDefinition = "varchar(200) COMMENT '用户邮箱'  ")
    @ExcelProperty("用户地址")
    private String sysUserAddress;

    @Column(columnDefinition = "char(1) DEFAULT '否'  COMMENT '是否锁定'")
    @ApiModelProperty(value = "用户是否锁定")
    @ExcelIgnore
    private String sysUserIsLock;

    @Column(columnDefinition = "tinyint(3) unsigned DEFAULT 0 COMMENT '密码错误次数'")
    @ApiModelProperty(value = "用户密码输入错误次数", example = "1")
    @ExcelIgnore
    private Integer sysUserPsdWrongCount;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(columnDefinition = "datetime COMMENT '用户最后一次登录时间' ")
    @ApiModelProperty(value = "用户最后一次登录时间")
    @ExcelIgnore
    private Date sysUserLastLoginTime;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(columnDefinition = "datetime COMMENT '用户锁定时间' ")
    @ApiModelProperty(value = "用户锁定时间")
    @ExcelIgnore
    private Date sysUserLockTime;

    @Column(columnDefinition = "varchar(200) COMMENT '用户邮箱'  ")
    @ApiModelProperty(value = "用户简介描述")
    @ExcelProperty("用户简介描述")
    private String sysUserRemark;

    @Transient
    @TableField(exist = false)
    // @Column(columnDefinition = "bigint(20) unsigned  COMMENT '用户所属的部门id'")
    @ApiModelProperty(value = "用户所属的部门id", example = "2")
    @ExcelIgnore
    private Long sysUserInfoDepartmentId;


    @JsonIgnore
    @ManyToMany(fetch = FetchType.EAGER) // 指定多对多关系
    @Cascade(value = {org.hibernate.annotations.CascadeType.ALL}) // 设置级联关系
    @JoinTable(name = "dream_sys_user_role", // 指定第三张中间表名称
            joinColumns = {@JoinColumn(name = "sys_user_id")}, // 本表主键userId与第三张中间表user_role_tb的外键user_role_tb_user_id对应
            inverseJoinColumns = {@JoinColumn(name = "sys_role_id")}) // 多对多关系另一张表与第三张中间表表的外键的对应关系
    @NotFound(action = NotFoundAction.IGNORE) // NotFound : 意思是找不到引用的外键数据时忽略，NotFound默认是exception
    @TableField(exist = false)
    @ExcelIgnore
    private Set<SysRole> rolesSet = new HashSet<>();

    @Transient
    @TableField(exist = false)
    @ExcelIgnore
    private String Pass;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<>();
        // 根据角色控制
        Set<SysRole> roles = this.getRolesSet();
        // 根据权限控制
        // Set<Permission> permissions=this.getPermissionSet();
        for (SysRole role : roles) {
            auths.add(new SimpleGrantedAuthority(role.getSysRoleTrueName()));
        }
        System.out.println("当前用户拥有的权限为=====>" + auths);
        return auths;
    }

    @Override
    public String getPassword() {
        return this.userPassword;
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    /**
     * 账户是否未过期 指示用户的帐户是否已过期。过期的帐户无法验证。
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账户是否未锁定 指示用户是否锁定或解锁。无法对锁定用户进行身份验证。
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 指示用户的凭据(密码)是否已过期。过期凭据阻止身份验证。
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 指示用户是否启用或禁用。无法对禁用用户进行身份验证。
     */
    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public String toString() {
        return "SysUser{" +
                ", userName='" + userName + '\'' +
                ", userPassword='" + userPassword + '\'' +
                ", sysUserAge=" + sysUserAge +
                ", sysUserBirthday=" + sysUserBirthday +
                ", sysUserPhone='" + sysUserPhone + '\'' +
                ", sysUserSex=" + sysUserSex +
                ", sysUserEmail='" + sysUserEmail + '\'' +
                ", sysUserAddress='" + sysUserAddress + '\'' +
                ", sysUserIsLock='" + sysUserIsLock + '\'' +
                ", sysUserPsdWrongCount=" + sysUserPsdWrongCount +
                ", sysUserLastLoginTime=" + sysUserLastLoginTime +
                ", sysUserLockTime=" + sysUserLockTime +
                ", sysUserRemark='" + sysUserRemark + '\'' +
                ", sysUserInfoDepartmentId=" + sysUserInfoDepartmentId +
                ", Pass='" + Pass + '\'' +
                '}';
    }

    public static void main(String[] args) {
        SysUser user = new SysUser();
        user.setUserName("陈小佳");
        user.setUserPassword("Cyj123456");
        // 加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(user.getUserPassword().trim());
        System.out.println(encodedPassword);


        String arr = "http://123123123123123123";
        String[] lists = arr.split("//");
        System.out.println(lists[0] + "list=====>" + lists[1]);

        String arrs = "http://123123123123123123";
        String lists2 = arrs.replace("http://", "");
        System.out.println("lists2=====>" + lists2);
    }

}
